import React, { useMemo, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../store";
import ListItem from "../../components/listItem";
import {
  Stepper,
  Checkbox,
  SubmitBar,
  Button,
  Space,
  Dialog,
} from "react-vant";
import {
  addCarItemCountAction,
  subCarItemCountAction,
  switchCarItemAction,
  modifyAllCarItemCheckAction,
  deleteCarItemsAction,
} from "../../store/car/carAction";
import style from "./style.module.css";
import { useCar } from "../../store/hooks";
const Index: React.FC = () => {
  const car = useSelector((state: RootState) => state.car.car);
  const dispatch = useDispatch();
  const addCarItemCount = (id: string) => dispatch(addCarItemCountAction(id));
  const subCarItemCount = (id: string) => dispatch(subCarItemCountAction(id));
  const switchCarItem = (id: string) => dispatch(switchCarItemAction(id));
  const deleteCarItems = () => {
    Dialog.confirm({
      title: "删除",
      message: "确认要删除选中的商品吗？",
    })
      .then(() => {
        dispatch(deleteCarItemsAction());
      }).catch(() => {})
  };
  const modifyAllCarItemCheck = (check: boolean) =>
    dispatch(modifyAllCarItemCheckAction(check));
  const [isEdit, setIsEdit] = useState(false);
  const { allCount, allPrice, allCheck } = useCar();
  return (
    <div>
      <div className={style["right"]}>
        <Space>
          {isEdit && (
            <Button size="small" type="danger" onClick={deleteCarItems}>
              删除
            </Button>
          )}
          <Button
            size="small"
            type="primary"
            onClick={() => setIsEdit(!isEdit)}
          >
            {isEdit ? "完成" : "编辑"}
          </Button>
        </Space>
      </div>
      <div>
        {car.map((v) => {
          return (
            <div key={v.id} className={style["between"]}>
              <Checkbox
                checked={v.isChecked}
                onChange={() => switchCarItem(v.id)}
                className={style["checkbox"]}
              />
              <ListItem
                id={v.id}
                price={v.price}
                title={v.title}
                desc={v.desc}
                url={v.url}
                key={v.id}
              >
                <Stepper
                  value={v.count}
                  onPlus={() => addCarItemCount(v.id)}
                  onMinus={() => subCarItemCount(v.id)}
                />
              </ListItem>
            </div>
          );
        })}
      </div>

      <SubmitBar price={allPrice * 100} buttonText="提交订单">
        <Checkbox
          checked={allCheck}
          onChange={(checked) => {
            modifyAllCarItemCheck(checked);
          }}
        >
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Index;
